# -*- coding: utf-8 -*-
"""
商品业务逻辑层

负责商品相关的业务逻辑处理
"""
import math
from typing import List, Dict, Any, Optional
from app.repositories.goods_repository import (
    GoodsRepository, 
    GoodsCommentsRepository, 
    GoodsBrandRepository,
    GoodsClassRepository
)
import logging

logger = logging.getLogger(__name__)

class GoodsService:
    """商品业务逻辑类"""
    
    def __init__(self):
        self.goods_repo = GoodsRepository()
        self.comments_repo = GoodsCommentsRepository()
        self.brand_repo = GoodsBrandRepository()
        self.category_repo = GoodsClassRepository()
    
    def get_goods_list(self, page: int = 1, page_size: int = 10, **filters) -> Dict[str, Any]:
        """获取商品列表"""
        try:
            result = self.goods_repo.get_goods_list(page, page_size, **filters)
            return {
                'code': 200,
                'message': '获取商品列表成功',
                'data': result
            }
        except Exception as e:
            logger.error(f"获取商品列表失败: {str(e)}")
            return {
                'code': 500,
                'message': f'获取商品列表失败: {str(e)}',
                'data': None
            }
    
    def get_goods_detail(self, goods_id: str, include_specs: bool = True) -> Dict[str, Any]:
        """获取商品详情"""
        try:
            result = self.goods_repo.get_goods_detail(goods_id, include_specs)
            
            if not result:
                return {
                    'code': 404,
                    'message': '商品不存在',
                    'data': None
                }
            
            return {
                'code': 200,
                'message': '获取商品详情成功',
                'data': result
            }
        except Exception as e:
            logger.error(f"获取商品详情失败: {str(e)}")
            return {
                'code': 500,
                'message': f'获取商品详情失败: {str(e)}',
                'data': None
            }
    
    def get_goods_specs(self, goods_id: str, include_barcodes: bool = True) -> Dict[str, Any]:
        """获取商品规格列表"""
        if not goods_id:
            raise ValueError("商品ID不能为空")
        
        # 检查商品是否存在
        goods = self.goods_repo.find_by_id("goods_id", goods_id)
        if not goods:
            raise ValueError("商品不存在")
        
        specs = self.goods_repo.find_specs_by_goods_id(goods_id, include_barcodes)
        
        return {
            "goods_id": goods_id,
            "specs": specs,
            "total": len(specs)
        }
    
    def get_goods_by_barcode(self, barcode: str) -> Dict[str, Any]:
        """通过条码查询商品"""
        if not barcode:
            raise ValueError("条码不能为空")
        
        goods = self.goods_repo.find_by_barcode(barcode)
        if not goods:
            raise ValueError("商品不存在")
        
        return goods
    
    def get_goods_comments(self, goods_id: str, page: int = 1, 
                          page_size: int = 10) -> Dict[str, Any]:
        """获取商品评论列表"""
        if not goods_id:
            raise ValueError("商品ID不能为空")
        
        # 验证分页参数
        if page <= 0:
            page = 1
        if page_size <= 0 or page_size > 100:
            page_size = 10
        
        # 检查商品是否存在
        goods = self.goods_repo.find_by_id("goods_id", goods_id)
        if not goods:
            raise ValueError("商品不存在")
        
        try:
            result = self.comments_repo.find_comments_by_goods_id(goods_id, page, page_size)
            
            # 处理图片数据
            for comment in result["items"]:
                if comment.get('images'):
                    comment['images'] = comment['images'].split(',') if comment['images'] else []
                else:
                    comment['images'] = []
            
            return {
                "code": 200,
                "message": "success",
                "data": {
                    "total": result["total"],
                    "page": page,
                    "pageSize": page_size,
                    "totalPages": math.ceil(result["total"] / page_size),
                    "list": result["items"]
                }
            }
            
        except Exception as e:
            # 如果数据库表不存在，返回模拟数据
            if "doesn't exist" in str(e) or "Table" in str(e):
                return self._get_mock_comments(goods_id, page, page_size)
            else:
                raise e
    
    def _get_mock_comments(self, goods_id: str, page: int, page_size: int) -> Dict[str, Any]:
        """获取模拟评论数据"""
        mock_comments = [
            {
                "comment_id": "1",
                "goods_id": goods_id,
                "customer_name": "张三",
                "customer_avatar": "https://example.com/avatar1.jpg",
                "rating": 5,
                "comment": "商品质量很好，包装也很精美，发货速度快，非常满意！",
                "images": ["https://example.com/review1.jpg", "https://example.com/review2.jpg"],
                "created_time": "2024-01-15 10:30:00",
                "reply_content": "感谢您的好评，我们会继续努力提供更好的产品和服务！",
                "reply_time": "2024-01-15 14:20:00",
                "goods_name": "示例商品",
                "goods_no": "SP001"
            },
            {
                "comment_id": "2",
                "goods_id": goods_id,
                "customer_name": "李四",
                "customer_avatar": "https://example.com/avatar2.jpg",
                "rating": 4,
                "comment": "整体不错，性价比很高，就是物流稍微慢了一点。",
                "images": [],
                "created_time": "2024-01-14 16:45:00",
                "reply_content": None,
                "reply_time": None,
                "goods_name": "示例商品",
                "goods_no": "SP001"
            },
            {
                "comment_id": "3",
                "goods_id": goods_id,
                "customer_name": "王五",
                "customer_avatar": "https://example.com/avatar3.jpg",
                "rating": 5,
                "comment": "超级棒！推荐购买，下次还会再来的。",
                "images": ["https://example.com/review3.jpg"],
                "created_time": "2024-01-13 09:15:00",
                "reply_content": "谢谢您的支持！",
                "reply_time": "2024-01-13 11:30:00",
                "goods_name": "示例商品",
                "goods_no": "SP001"
            }
        ]
        
        # 模拟分页
        start_idx = (page - 1) * page_size
        end_idx = start_idx + page_size
        paginated_comments = mock_comments[start_idx:end_idx]
        
        return {
            "code": 200,
            "message": "success (mock data)",
            "data": {
                "total": len(mock_comments),
                "page": page,
                "pageSize": page_size,
                "totalPages": math.ceil(len(mock_comments) / page_size),
                "list": paginated_comments
            }
        }
    
    def get_brands(self, brand_name: Optional[str] = None, page: int = 1, 
                  page_size: int = 10) -> Dict[str, Any]:
        """获取品牌列表"""
        
        # 验证分页参数
        if page <= 0:
            page = 1
        if page_size <= 0 or page_size > 100:
            page_size = 10
        
        result = self.brand_repo.find_brands_with_search(
            brand_name=brand_name,
            page=page,
            page_size=page_size
        )
        
        return {
            "total": result["total"],
            "items": result["items"]
        }
    
    def get_banners(self, status: Optional[int] = 1, limit: int = 10) -> Dict[str, Any]:
        """获取轮播图列表"""
        try:
            # 这里可以从数据库获取真实数据，暂时返回模拟数据
            # TODO: 创建 BannerRepository 从数据库获取轮播图数据
            banners = self._get_mock_banners(status, limit)
            
            return {
                "code": 200,
                "message": "success",
                "data": banners
            }
        except Exception as e:
            raise Exception(f"获取轮播图失败: {str(e)}")
    
    def _get_mock_banners(self, status: Optional[int] = 1, limit: int = 10) -> List[Dict[str, Any]]:
        """获取模拟轮播图数据"""
        mock_banners = [
            {
                "id": 1,
                "title": "新品上市",
                "image": "https://img0.baidu.com/it/u=2091626457,2794242804&fm=253&fmt=auto&app=138&f=JPEG?w=801&h=800",
                "link_type": "goods",
                "link_value": "G001",
                "sort": 1,
                "status": 1
            },
            {
                "id": 2,
                "title": "限时促销",
                "image": "https://img0.baidu.com/it/u=3235324482,3907534166&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=708",
                "link_type": "category",
                "link_value": "C001",
                "sort": 2,
                "status": 1
            },
            {
                "id": 3,
                "title": "品牌专区",
                "image": "https://img1.baidu.com/it/u=1521785368,3470917835&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=800",
                "link_type": "url",
                "link_value": "https://example.com/brand",
                "sort": 3,
                "status": 1
            },
            {
                "id": 4,
                "title": "夏季新品",
                "image": "https://img0.baidu.com/it/u=2179415447,67475942&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=635",
                "link_type": "goods",
                "link_value": "G002",
                "sort": 4,
                "status": 1
            },
            {
                "id": 5,
                "title": "优惠活动",
                "image": "https://img0.baidu.com/it/u=1422230622,1775692863&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=771",
                "link_type": "category",
                "link_value": "C002",
                "sort": 5,
                "status": 0
            }
        ]
        
        # 根据状态筛选
        if status is not None:
            mock_banners = [banner for banner in mock_banners if banner["status"] == status]
        
        # 按排序字段排序
        mock_banners.sort(key=lambda x: x["sort"])
        
        # 限制返回数量
        return mock_banners[:limit]
    
    def get_categories(self, class_name: Optional[str] = None, page: int = 1, 
                      page_size: int = 10, include_goods_count: bool = False) -> Dict[str, Any]:
        """获取分类列表"""
        # 验证分页参数
        if page <= 0:
            page = 1
        if page_size <= 0 or page_size > 100:
            page_size = 10
        
        try:
            result = self.category_repo.find_categories_with_search(
                class_name=class_name,
                page=page,
                page_size=page_size
            )
            
            # 如果需要包含商品数量
            if include_goods_count:
                for category in result["items"]:
                    goods_count = self.category_repo.find_goods_count_by_category(category["class_id"])
                    category["goods_count"] = goods_count
            
            return {
                "code": 200,
                "message": "success",
                "data": {
                    "total": result["total"],
                    "page": page,
                    "pageSize": page_size,
                    "totalPages": math.ceil(result["total"] / page_size),
                    "list": result["items"]
                }
            }
        except Exception as e:
            raise Exception(f"获取分类列表失败: {str(e)}")
    
    def get_all_categories(self, include_goods_count: bool = False) -> Dict[str, Any]:
        """获取所有分类（用于构建树形结构）"""
        try:
            categories = self.category_repo.find_all_categories()
            
            # 如果需要包含商品数量
            if include_goods_count:
                for category in categories:
                    goods_count = self.category_repo.find_goods_count_by_category(category["class_id"])
                    category["goods_count"] = goods_count
            
            return {
                "code": 200,
                "message": "success",
                "data": categories
            }
        except Exception as e:
            raise Exception(f"获取所有分类失败: {str(e)}")
    
    def get_goods_categories(self, parent_id: str = "0", page: int = 1, page_size: int = 20) -> Dict[str, Any]:
        """获取商品分类"""
        try:
            result = self.goods_repo.get_goods_categories(parent_id, page, page_size)
            return {
                'code': 200,
                'message': '获取商品分类成功',
                'data': result
            }
        except Exception as e:
            logger.error(f"获取商品分类失败: {str(e)}")
            return {
                'code': 500,
                'message': f'获取商品分类失败: {str(e)}',
                'data': None
            }
    
    def get_goods_brands(self, limit: int = 20) -> Dict[str, Any]:
        """获取商品品牌"""
        try:
            result = self.goods_repo.get_goods_brands(limit)
            return {
                'code': 200,
                'message': '获取商品品牌成功',
                'data': result
            }
        except Exception as e:
            logger.error(f"获取商品品牌失败: {str(e)}")
            return {
                'code': 500,
                'message': f'获取商品品牌失败: {str(e)}',
                'data': None
            } 